#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <memory>
#include "log.hpp"

using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << " please use: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    // 创建套接字：
    int sd = socket(AF_INET, SOCK_DGRAM, 0); // 网络通信/用户数据报
    if (sd < 0)
        use_log(loglevel::DEBUG) << "socket failure!";
    use_log(loglevel::DEBUG) << "socket success!";
    // os自己认识用户端机器的ip+随机会生成端口号port自动绑定与解除;故无需bind/程序终止立刻解除故查不到状态

    string ip = argv[1];           // string内置机制不会直接拷贝指针
    uint16_t port = stoi(argv[2]); // 先构造string
   //初始化des套接字：
    sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());
//死循环式等待给服务端发送信息： 
    while (1)
    {
        string mess;
        getline(cin, mess);
        socklen_t len = sizeof(local);
        //发送：
        int so = sendto(sd, mess.c_str(), mess.size(), 0, (sockaddr *)&local, len); // 输入型参数
        if (so < 0)
            use_log(loglevel::DEBUG) << "sendto failure!";
     //接收：
        char buff[1024] = {0};
        ssize_t rm= recvfrom(sd, buff, sizeof(buff) - 1, 0, (sockaddr *)&local, &len);
        if (rm< 0)  use_log(loglevel::DEBUG) << "recvfrom failure!";

        cout<<"$server say:"<< buff<<endl;;
    }
}